from django.contrib import admin
from .models import Todo

# Register your models here.

@admin.register(Todo)
class TodoAdmin(admin.ModelAdmin):
    list_display = ('title', 'user', 'status', 'priority', 'due_date', 'created_at')
    list_filter = ('status', 'priority', 'created_at')
    search_fields = ('title', 'description', 'user__email', 'user__username')
    ordering = ('-created_at',)
    
    # 编辑表单中显示的字段
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'user')
        }),
        ('状态信息', {
            'fields': ('status', 'priority', 'due_date')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            # 'classes': ('collapse',)  # 可折叠
        }),
    )
    
    # 只读字段
    readonly_fields = ('created_at', 'updated_at')
    
    def save_model(self, request, obj, form, change):
        """保存模型时，如果是新建，则设置用户为当前用户"""
        if not change:  # 如果是新建
            obj.user = request.user
        super().save_model(request, obj, form, change)
